package tech.aistar.controller;

import tech.aistar.pojo.User;
import tech.aistar.service.IUserService;
import tech.aistar.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author Ray
 * @version 1.0
 * @description:本类用来演示:控制层
 * @date 2019/9/5  16:42
 */
@WebServlet(urlPatterns = "/user/login")
public class LoginCiAction extends HttpServlet {
    private IUserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理中文乱码
        req.setCharacterEncoding("utf-8");

        //根据请求的参数名称来获取请求的参数
        String username = req.getParameter("username");
//        System.out.println("username"+username);
        String password = req.getParameter("password");
//        System.out.println("password"+password);


        //控制层调用service层 调用mapper层
        User user = userService.findByUsername(username);

        if (user != null) {
            //用户存在
            if (user.getPassword().equals(password)) {

                String flag = req.getParameter("flag");//默认值是on - 勾选
                if(flag!=null) {
                    //将用户名和密码保存到cookie - 发送到客户端
                    username = URLEncoder.encode(URLEncoder.encode(username, "utf-8"), "utf-8");

                    Cookie c = new Cookie("userLogin", username + ":" + password);

                    //设置cookie的生命周期
                    c.setMaxAge(24 * 60 * 60 * 7);//一周免登陆

                    //设置path - 必须要设置
                    c.setPath("/");

                    //通过响应头信息将cookie返回给客户端
                    resp.addCookie(c);
                }else{
                    Cookie c = new Cookie("userLogin","");
                    c.setPath("/");
                    resp.addCookie(c);
                }


                //将用户存在session
                req.getSession().setAttribute("user",user);


                //重定向
                resp.sendRedirect(req.getContextPath()+"/phone/list");

            } else {
                //密码错误
                //重定向
                resp.sendRedirect(req.getContextPath()+"/prj/user/login.jsp?error=1");
            }

        }else {
            //用户不存在
            resp.sendRedirect(req.getContextPath()+"/prj/user/login.jsp?error=0");
        }

    }
}
